package com.xkcyy.one.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xkcyy.one.dto.MessageDTO;
import com.xkcyy.one.dto.MessageRequestDTO;
import com.xkcyy.one.entity.Conversation;
import com.xkcyy.one.entity.Message;
import com.xkcyy.one.exception.BusinessException;
import com.xkcyy.one.mapper.ConversationMapper;
import com.xkcyy.one.mapper.MessageMapper;
import com.xkcyy.one.ai.llm.OpenAiClient;
import com.xkcyy.one.ai.llm.model.ChatMessage;
import com.xkcyy.one.ai.llm.model.ChatResult;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import reactor.core.publisher.Flux;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 消息服务实现类
 *
 * @author yuand
 */
@Service
@AllArgsConstructor
public class MessageService {

    private final MessageMapper messageMapper;
    private final ConversationMapper conversationMapper;
    private final OpenAiClient openAiClient;

    /**
     * 获取所有消息
     *
     * @return 消息DTO列表
     */
    public List<MessageDTO> getAllMessages() {
        List<Message> messages = messageMapper.selectList(null);
        return messages.stream()
                .map(MessageDTO::fromEntity)
                .collect(Collectors.toList());
    }

    /**
     * 根据ID获取消息
     *
     * @param id 消息ID
     * @return 消息DTO
     */
    public MessageDTO getMessageById(Long id) {
        Message message = messageMapper.selectById(id);
        if (message == null) {
            throw new BusinessException("消息不存在，ID: " + id);
        }
        return MessageDTO.fromEntity(message);
    }

    /**
     * 根据对话ID获取消息列表
     *
     * @param conversationId 对话ID
     * @return 消息DTO列表
     */
    public List<MessageDTO> getMessagesByConversationId(Long conversationId) {
        // 检查对话是否存在
        Conversation conversation = conversationMapper.selectById(conversationId);
        if (conversation == null) {
            throw new BusinessException("对话不存在，ID: " + conversationId);
        }

        // 查询对话的消息列表
        LambdaQueryWrapper<Message> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Message::getConversationId, conversationId);
        queryWrapper.orderByAsc(Message::getCreateTime);

        List<Message> messages = messageMapper.selectList(queryWrapper);
        return messages.stream()
                .map(MessageDTO::fromEntity)
                .collect(Collectors.toList());
    }

    /**
     * 创建消息
     *
     * @param message 消息实体
     * @return 消息DTO
     */
    @Transactional(rollbackFor = Exception.class)
    public MessageDTO createMessage(Message message) {
        // 检查对话是否存在
        Conversation conversation = conversationMapper.selectById(message.getConversationId());
        if (conversation == null) {
            throw new BusinessException("对话不存在，ID: " + message.getConversationId());
        }

        // 插入消息
        messageMapper.insert(message);

        return MessageDTO.fromEntity(message);
    }

    /**
     * 处理用户消息
     *
     * @param messageRequest 消息请求DTO
     * @return 消息DTO
     */
    @Transactional(rollbackFor = Exception.class)
    public MessageDTO processUserMessage(MessageRequestDTO messageRequest) {
        // 检查对话是否存在
        Conversation conversation = conversationMapper.selectById(messageRequest.getConversationId());
        if (conversation == null) {
            throw new BusinessException("对话不存在，ID: " + messageRequest.getConversationId());
        }

        // 创建用户消息实体
        Message userMessage = Message.create(Message.class);
        userMessage.setConversationId(messageRequest.getConversationId());
        userMessage.setContent(messageRequest.getContent());
        userMessage.setRole(Message.Role.USER);
        userMessage.setReasonContent(messageRequest.getReasonContent());
        messageMapper.insert(userMessage);

        // 获取对话历史
        List<MessageDTO> conversationHistory = getMessagesByConversationId(messageRequest.getConversationId());

        // 生成AI回复
        String aiResponse = "";// aiService.generateResponse(conversationHistory);

        // 创建助手消息实体
        Message assistantMessage = Message.create(Message.class);
        assistantMessage.setConversationId(messageRequest.getConversationId());
        assistantMessage.setContent(aiResponse);
        assistantMessage.setRole(Message.Role.ASSISTANT);
        assistantMessage.setReasonContent(""); // 初始化为空，后续可能会填充
        messageMapper.insert(assistantMessage);

        // 更新对话实体
        conversation.setUpdateTime(LocalDateTime.now());
        conversationMapper.updateById(conversation);

        return MessageDTO.fromEntity(assistantMessage);
    }

    /**
     * 保存用户消息并获取对话历史（用于流式响应）
     *
     * @param messageRequest 消息请求DTO
     * @return 用户消息DTO
     */
    @Transactional(rollbackFor = Exception.class)
    public MessageDTO saveUserMessageAndGetHistory(MessageRequestDTO messageRequest) {
        // 检查对话是否存在
        Conversation conversation = conversationMapper.selectById(messageRequest.getConversationId());
        if (conversation == null) {
            throw new BusinessException("对话不存在，ID: " + messageRequest.getConversationId());
        }

        // 创建用户消息实体
        Message userMessage = Message.create(Message.class);
        userMessage.setConversationId(messageRequest.getConversationId());
        userMessage.setContent(messageRequest.getContent());
        userMessage.setRole(Message.Role.USER);
        userMessage.setReasonContent(messageRequest.getReasonContent());

        // 插入消息
        messageMapper.insert(userMessage);

        // 更新对话实体
        conversation.setUpdateTime(LocalDateTime.now());
        conversationMapper.updateById(conversation);

        return MessageDTO.fromEntity(userMessage);
    }

    /**
     * 更新消息
     *
     * @param message 消息实体
     * @return 消息DTO
     */
    @Transactional(rollbackFor = Exception.class)
    public MessageDTO updateMessage(Message message) {
        // 检查消息是否存在
        Message existingMessage = messageMapper.selectById(message.getId());
        if (existingMessage == null) {
            throw new BusinessException("消息不存在，ID: " + message.getId());
        }

        // 更新消息属性
        existingMessage.setContent(message.getContent());
        if (message.getRole() != null) {
            existingMessage.setRole(message.getRole());
        }
        if (message.getReasonContent() != null) {
            existingMessage.setReasonContent(message.getReasonContent());
        }
        existingMessage.setUpdateTime(LocalDateTime.now());

        // 更新消息
        messageMapper.updateById(existingMessage);

        return MessageDTO.fromEntity(existingMessage);
    }

    /**
     * 删除消息
     *
     * @param id 消息ID
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteMessage(Long id) {
        // 检查消息是否存在
        Message existingMessage = messageMapper.selectById(id);
        if (existingMessage == null) {
            throw new BusinessException("消息不存在，ID: " + id);
        }

        // 删除消息
        messageMapper.deleteById(id);
    }

    /**
     * 处理流式聊天请求
     *
     * @param messageRequest 消息请求DTO
     * @return 流式聊天结果
     * @author yuand
     */
    @Transactional(rollbackFor = Exception.class)
    public Flux<ChatResult> chatSteam(MessageRequestDTO messageRequest) {
        // 保存用户消息并获取对话历史
        saveUserMessageAndGetHistory(messageRequest);

        // 创建助手消息实体
        Message assistantMessage = Message.create(Message.class);
        assistantMessage.setConversationId(messageRequest.getConversationId());
        assistantMessage.setContent("");
        assistantMessage.setRole(Message.Role.ASSISTANT);
        assistantMessage.setReasonContent(""); // 初始化为空，流式响应完成后可能会填充

        // 插入消息
        messageMapper.insert(assistantMessage);
        MessageDTO savedAssistantMessageDTO = MessageDTO.fromEntity(assistantMessage);

        // 用于收集完整的响应内容
        StringBuilder fullContent = new StringBuilder();
        StringBuilder reasonContent = new StringBuilder();

        // 获取对话历史
        List<MessageDTO> messageHistory = getMessagesByConversationId(messageRequest.getConversationId());

        // 转换为ChatMessage列表
        List<ChatMessage> chatMessages = messageHistory.stream()
                .map(dto -> {
                    String role = Message.Role.ASSISTANT.equals(dto.getRole()) ? "assistant" : "user";
                    return ChatMessage.builder()
                            .role(role)
                            .content(dto.getContent())
                            .build();
                })
                .collect(Collectors.toList());

        // 生成流式响应，并传递消息ID以便客户端可以更新
        return openAiClient.chatStream(chatMessages)
                .doOnNext(chatResult -> {
                    if (chatResult.getContent() != null) {
                        fullContent.append(chatResult.getContent());
                    }
                    // 这里可以根据实际情况提取推理内容
                    // 如果ChatResult中有包含推理内容的字段，可以在这里填充reasonContent
                    if(chatResult.getReasoningContent()!=null){
                        reasonContent.append(chatResult.getReasoningContent());
                    }
                })
                .doOnComplete(() -> {
                    // 在流式响应完成后，更新消息内容
                    Message updateMsg = Message.create(Message.class, savedAssistantMessageDTO.getId());
                    updateMsg.setContent(fullContent.toString());
                    // 如果有收集到推理内容，也一并更新
                    if (reasonContent.length() > 0) {
                        updateMsg.setReasonContent(reasonContent.toString());
                    }
                    messageMapper.updateById(updateMsg);
                });
    }
}
